<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title></title>
  <script src="../vue.js" type="text/javascript" charset="utf-8"></script>
  <script src="./data.js"></script>
  <link rel="stylesheet" href="./index.css">
</head>

<body>
  <div id="app">
    <button @click="allChoose('10001')">全选</button>

    <button @click="allChoose('10002')">反选</button>
    <h1>总价：￥ {{ total || '0.00' }} 元 </h1>

    <!-- @calc="totalAll" 自定义事件计算总价 -->
    <cell @calc="totalAll" ref="cell" v-for="(item,index) in goods" :item="item" :key="index"></cell>


  </div>
</body>

<template id="box">
  <!-- 
    {
  title: '佛跳墙',
  price: 88.88,
  number: 1,
  message: '30天保价',
  img: '佛跳墙.jpg'
}
   -->
  <div class="box">
    <img @click="swi = !swi" class="cho" :src="choose" alt="">
    <img class="logo" :src="item.img" alt="">
    <h3> {{ item.title }} </h3>
    <h5>价格：￥ {{item.price}} </h5>
    <section>
      <button @click="calc('10086')">-</button>
      <input v-model="item.number" type="number" name="" id="">
      <button @click="calc('10010')">+</button>
    </section>
    <h1>总价：￥ {{ (item.price * item.number).toFixed(2) }} 元 </h1>
    <div class="msg" v-if="item.msg"> {{item.msg}} </div>
    <div class="message" v-if="item.message"> {{item.message}} </div>
  </div>
</template>

<script type="text/javascript">
  const app = Vue.createApp({
    data() {
      return {
        goods,
        total: null
      }
    },
    methods: {
      totalAll() {
        // 因为计算属性上来会执行一次，所以这里先做个判断，否则 this.$refs.cell 为空,.length就会报错
        if (!this.$refs.cell) return

        let total = 0
        for (let i = 0; i < this.$refs.cell.length; i++) {
          if (this.$refs.cell[i].swi == true) {
            total += this.$refs.cell[i].item.price * this.$refs.cell[i].item.number
          }
        }

        this.total = total.toFixed(2)
      },
      allChoose(type) {

        // 全选

        // console.log(this.$refs);
        for (let i = 0; i < this.$refs.cell.length; i++) {
          if (type == '10001') {
            this.$refs.cell[i].swi = true
          } else {
            this.$refs.cell[i].swi = !this.$refs.cell[i].swi
          }

        }

      }
    }
  })


  // 组件
  app.component('cell', {
    template: '#box',
    props: {
      item: Object
    },
    data() {
      return {
        swi: false
      }
    },
    computed: {
      choose() {
        this.$emit('calc')
        return this.swi ? './choose2.png' : './choose.png'
      }
    },
    methods: {
      calc(type) {
        this.$emit('calc')
        if (type == '10086') {
          // 减
          this.item.number = this.item.number <= 1 ? 1 : this.item.number - 1
        } else {
          // 加
          this.item.number++
        }
      }
    },
  })

  app.mount('#app')
</script>

</html>